package com.musiklegal;




import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Friend extends Activity {
	ProgressDialog dialog;
	ListView lvm;
	HttpClient flist;
	FbAdapter adapter;
	HttpGet get;
	HttpResponse fresp ;
	HttpEntity frlist;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr;
	FBParser fparse;
	String addres;
	CatalogueParser cp;
	static List<Fbdata> fbd=new ArrayList<Fbdata>();;
	int offset=1;
	TextView tv;
	EditText srctxt;
	Handler h;
	List<Fbdata> cari = new ArrayList<Fbdata>();
	 AlertDialog alertDialog;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        h = new Handler();
        setContentView(R.layout.fblist);
        //showDialog(0);
        alertDialog= new AlertDialog.Builder(Friend.this).create();
		alertDialog.setTitle("Error");
		alertDialog.setMessage(Settings.gakonek);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
			public void onClick(DialogInterface dialog, int which) {
			finish();
			}
		});
		alertDialog.setIcon(R.drawable.oc2);
        new Thread(new Runnable(){

			public void run() {
				
				
						
						  if(MusikLegal.internet(getApplicationContext())){
					        	fbd.clear();
					        	
					        
					        	
								flist = new DefaultHttpClient(); 
								addres = "http://secure.musiklegal.com/?action=socialnet&method=friends&username="+MusikLegal.mPreferences.getString("UserName", "NoUser")+"&limit=25&offset=";
								Log.d("url",addres);
								get = new HttpGet(addres+1);
								try {
									fresp = flist.execute(get);
								} catch (ClientProtocolException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								frlist = fresp.getEntity();
								spf = SAXParserFactory.newInstance();
								try {
									sp = spf.newSAXParser();
									xr = sp.getXMLReader();
								} catch (ParserConfigurationException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SAXException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
								
								fparse = new FBParser();
								xr.setContentHandler(fparse);
								try {
									xr.parse(retrieveInputStream(frlist));
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (SAXException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
							
					        
							friends();
							
							 //System.gc();
						}
					        else
					        {
					        
							h.post(new Runnable(){

								public void run() {
									// TODO Auto-generated method stub
									alertDialog.show();
								}});
							
					        }  
						
						
						
					
				
			}}).start();
      
	}
	
	public void onResume()
	{
		super.onResume();
		new Thread(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				if(!MusikLegal.internet(getApplicationContext()))
				{
					
					h.post(new Runnable(){

						public void run() {
							// TODO Auto-generated method stub
							finish();
						}});
					
				}
			}}).start();
		
		OnlineC.catl.clear();
	}
	
	
	void friends()
	{
		//removeDialog(0);
		if(MusikLegal.internet(getApplicationContext())){
        
        tv = (TextView)findViewById(R.id.TextView01);
        h.post(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				tv.setText(Settings.jteman);
			}});
		
		srctxt = (EditText) findViewById(R.id.searchs);
        lvm=(ListView)findViewById(R.id.FbView);
        
        adapter = new FbAdapter(this,fbd);
        h.post(new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				 lvm.setAdapter(adapter);
			}});
       
        lvm.setTextFilterEnabled(true);
        lvm.setOnScrollListener(new OnScrollListener(){

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastitem = firstVisibleItem + visibleItemCount;
				if(lastitem == totalItemCount-1)
					{
					if(offset+24<=fbd.size()){
           			 try {
           				 offset+=25;
						 get = new HttpGet(addres+offset);
						 fresp = flist.execute(get);
						 frlist = fresp.getEntity();
               			 spf = SAXParserFactory.newInstance();
               			 sp = spf.newSAXParser();
               			xr = sp.getXMLReader();
               			fparse = new FBParser();
            			xr.setContentHandler(fparse);
               			xr.parse(retrieveInputStream(frlist));
               			lvm.invalidateViews();
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ParserConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SAXException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					}
					}
				
			}

			public void onScrollStateChanged(AbsListView view,
					int scrollState) {
			}});
        lvm.setOnItemClickListener(new OnItemClickListener() 
        {
          public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
          {
        	  /*

        		try 
        		{
        			flist = new DefaultHttpClient(); 
        			get = new HttpGet("http://secure.musiklegal.com/?action=socialnet&method=friend_top_play&username="+fbd.get(position).use);
        			fresp = flist.execute(get);

        			frlist = fresp.getEntity();
        			spf = SAXParserFactory.newInstance();
        			sp = spf.newSAXParser();
        			xr = sp.getXMLReader();
        			
        			cp = new CatalogueParser();
        			xr.setContentHandler(cp);
        			xr.parse(retrieveInputStream(frlist));
        			OnlineC.catl.addAll(cp.catl);
				} 
        		catch (ClientProtocolException e) {
					
					e.printStackTrace();
					finish();
				} catch (IOException e) {
					
					e.printStackTrace();
					finish();
				}
				catch (SAXException e) {
					
					e.printStackTrace();
					finish();
					
				} catch (ParserConfigurationException e) {
				
					e.printStackTrace();
				}
        	
			CatalogueList.name = fbd.get(position).name;
			TrackInfo.fromFriend=true;
			TrackInfo.isCatalogue=true;
	        Intent i = new Intent(getApplicationContext(), CatalogueList.class);
			startActivity(i);*/
        	  
        	  
        	  Profile.username = fbd.get(position).use;
        	  TrackInfo.fromFriend=true;
  			  TrackInfo.isCatalogue=true;
        	  startActivity(new Intent(Friend.this,Profile.class));
          }
         
        });
        
         Button searchs = (Button) this.findViewById(R.id.srcs);
		 searchs.setOnClickListener(new OnClickListener() 
        {
              public void onClick(View v) 
              {
            	  
            	  showDialog(0);
            	  new Thread(new Runnable(){

					public void run() {
						h.post(new Runnable(){

							public void run() {
								
								 fbd.clear();
				            	  OnlineC.catl.clear();

									
										try
							           	   {
							           		        
							         			 	String srch = srctxt.getText().toString().replace(" ", "+");
							         			 	offset=1;
							         			 	if(srch.compareTo("")==0)
							         			 		addres = "http://secure.musiklegal.com/?action=socialnet&method=friends&username="+MusikLegal.mPreferences.getString("UserName", "NoUser");
							         			 	else
							         			 		addres ="http://secure.musiklegal.com/?action=socialnet&method=friends&username="+MusikLegal.mPreferences.getString("UserName", "NoUser")+"&filter="+srch;
							           		     get = new HttpGet(addres);
							           		     
							           			 fresp = flist.execute(get);
							           			 frlist = fresp.getEntity();
							           			 spf = SAXParserFactory.newInstance();
							           			 sp = spf.newSAXParser();
							           			 xr = sp.getXMLReader();
							                 	FBParser fbp = new FBParser();
							           			xr.setContentHandler(fbp);
							           			xr.parse(retrieveInputStream(frlist));
							           			
							           			lvm.invalidateViews();
							           			friends();
							           			removeDialog(0);
							           			
							           	   }
							           	   catch (Exception e) {
									              }
										
								
							}});
						
					}}).start();
            	 
					
           	   
           	   
              }
        });
		}
		else
        {
			h.post(new Runnable(){

				public void run() {
					// TODO Auto-generated method stub
					alertDialog.show();
				}});
		
        }
		
	}
	
	

	protected Dialog onCreateDialog(int id) {
        switch (id) {
              case 0: {
                    dialog = new ProgressDialog(this);
                    dialog.setMessage("Loading...");
                    dialog.setIndeterminate(true);
                    dialog.setCancelable(false);
                    return dialog;                   
              }
        }
        return null;
  }
	public void onDestroy()
	{
		System.gc();
		if(adapter!=null)
		adapter.clear();
		super.onDestroy();
	}
	
	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  }
	
	 public boolean onCreateOptionsMenu(Menu menu){

		

		menu.add(0,MainMenu.TopUp,0,Settings.topup);
		
		menu.add(0,MainMenu.About,0,"About");

		return true;

		}
	public boolean onOptionsItemSelected (MenuItem item){

		switch (item.getItemId()){

		case MainMenu.TopUp :
			startActivity(new Intent(getApplicationContext(), TopUp.class));

		return true;
		
		case MainMenu.Subs:
			startActivity(new Intent(getApplicationContext(), Subscription.class));
		return true;
		
		case MainMenu.About:
			Toast.makeText(getApplicationContext(), MusikLegal.mPreferences.getString("UserName", "default"), Toast.LENGTH_SHORT).show();
			
			return true;
		}
		return false;
	}
	
	
	
	
}
	